package com.chuangshu.chuangshuteam.controller;

import com.chuangshu.chuangshuteam.annotation.RequiresPermissions;
import com.chuangshu.chuangshuteam.config.BaseContext;
import com.chuangshu.chuangshuteam.dto.Result;
import com.chuangshu.chuangshuteam.entity.TeamMember;
import com.chuangshu.chuangshuteam.entity.UserProfile;
import com.chuangshu.chuangshuteam.entity.Users;
import com.chuangshu.chuangshuteam.service.AuthService;
import com.chuangshu.chuangshuteam.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UsersController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private AuthService authService;

    /**
     * 微信授权登录接口 - 完整的微信小程序登录流程
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> loginRequest) {
        try {
            // 获取前端传来的code
            String code = loginRequest.get("code");
            if (code == null || code.isEmpty()) {
                log.error("微信登录失败: code为空");
                return Result.fail("登录失败：缺少code参数");
            }

            log.info("微信登录请求: code={}", code);

            // 获取用户信息
            String nickname = loginRequest.get("nickname");
            String avatarUrl = loginRequest.get("avatarUrl");

            // 调用新的微信登录方法（内部会处理code换取openid的逻辑）
            Users user = usersService.wechatLogin(code, nickname, avatarUrl);

            // 设置当前用户ID到线程局部变量
            BaseContext.setCurrentId(user.getId());

            log.info("微信登录成功: userId={}", user.getId());
            return Result.ok(user);
        } catch (Exception e) {
            log.error("微信登录失败: {}", e.getMessage(), e);
            return Result.fail("登录失败：" + e.getMessage());
        }
    }

    /**
     * 获取个人基本信息接口
     */
    @GetMapping("/profile")
    public Result getProfile() {
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            return Result.fail("用户未登录");
        }

        Users user = usersService.getProfile(currentUserId);
        if (user == null) {
            return Result.fail("用户不存在");
        }

        return Result.ok(user);
    }

    /**
     * 更新个人基本信息接口
     */
    @PutMapping("/profile")
    public Result updateProfile(@RequestBody Users user) {
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            return Result.fail("用户未登录");
        }

        // 检查是否修改自己的信息
        if (!currentUserId.equals(user.getId())) {
            return Result.fail("无权修改他人信息");
        }

        boolean success = usersService.updateProfile(user);
        if (success) {
            return Result.ok();
        } else {
            return Result.fail("更新失败");
        }
    }

    /**
     * 设置专业方向接口
     */
    @PutMapping("/direction")
    public Result setDirection(@RequestParam String direction) {
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            return Result.fail("用户未登录");
        }

        // 验证方向值是否有效
        String[] validDirections = {"frontend", "backend", "ui", "cv", "pm", "embedded", "general"};
        boolean isValid = false;
        for (String validDir : validDirections) {
            if (validDir.equals(direction)) {
                isValid = true;
                break;
            }
        }

        if (!isValid) {
            return Result.fail("无效的专业方向");
        }

        boolean success = usersService.setDirection(currentUserId, direction);
        if (success) {
            return Result.ok();
        } else {
            return Result.fail("方向设置失败");
        }
    }

    /**
     * 软删除用户接口（管理员）
     */
    @DeleteMapping("/{id}")
    @RequiresPermissions("user:delete")
    public Result deleteUser(@PathVariable Long id) {
        Long currentUserId = BaseContext.getCurrentId();

        boolean success = usersService.softDeleteUser(id, currentUserId);
        if (success) {
            return Result.ok();
        } else {
            return Result.fail("删除失败");
        }
    }

    /**
     * 获取用户列表接口（管理员）
     */
    @GetMapping("/list")
    @RequiresPermissions("user:list")
    public Result getUserList() {
        List<Users> users = usersService.getAllUsers();
        return Result.ok(users);
    }

    /**
     * 根据方向获取用户列表（方向负责人和管理员）
     */
    @GetMapping("/listByDirection")
    public Result getUsersByDirection(@RequestParam String direction) {
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            return Result.fail("用户未登录");
        }

        // 检查用户是否有权限访问该方向的数据
        if (!authService.hasDirectionPermission(currentUserId, direction)) {
            return Result.fail("无权限访问该方向数据");
        }

        List<Users> users = usersService.getUsersByDirection(direction);
        return Result.ok(users);
    }

    /**
     * 获取当前用户权限信息
     */
    @GetMapping("/authInfo")
    public Result getAuthInfo() {
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            return Result.fail("用户未登录");
        }

        // 获取用户权限信息
        boolean isAdmin = authService.isAdmin(currentUserId);
        List<String> directions = authService.getUserDirections(currentUserId);

        // 构建权限信息响应
        AuthInfoResponse authInfo = new AuthInfoResponse();
        authInfo.setAdmin(isAdmin);
        authInfo.setDirections(directions);
        authInfo.setPermissions(getUserPermissions(currentUserId));

        return Result.ok(authInfo);
    }

    /**
     * 获取用户权限列表
     */
    private List<String> getUserPermissions(Long userId) {
        // 简化实现，实际应该从数据库查询
        if (authService.isAdmin(userId)) {
            return List.of("user:delete", "user:list", "team:edit", "recruitment:all");
        } else if (authService.hasRole(userId, "leader")) {
            return List.of("recruitment:create", "recruitment:manage");
        } else {
            return List.of();
        }
    }

    /**
     * 权限信息响应类
     */
    private static class AuthInfoResponse {
        private boolean admin;
        private List<String> directions;
        private List<String> permissions;

        // getter and setter
        public boolean isAdmin() { return admin; }
        public void setAdmin(boolean admin) { this.admin = admin; }
        public List<String> getDirections() { return directions; }
        public void setDirections(List<String> directions) { this.directions = directions; }
        public List<String> getPermissions() { return permissions; }
        public void setPermissions(List<String> permissions) { this.permissions = permissions; }
    }
    /**
     * 获取个人完整信息（包含团队状态）
     */
    @GetMapping("/profile/complete")
    public Result getCompleteProfile() {
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            return Result.fail("用户未登录");
        }

        UserProfile profile = usersService.getProfileWithTeamInfo(currentUserId);
        if (profile == null) {
            return Result.fail("用户不存在");
        }

        return Result.ok(profile);
    }

    /**
     * 检查用户团队状态
     */
    @GetMapping("/team/status")
    public Result getTeamStatus() {
        Long currentUserId = BaseContext.getCurrentId();
        if (currentUserId == null) {
            return Result.fail("用户未登录");
        }

        boolean inTeam = usersService.isUserInTeam(currentUserId);
        TeamStatusResponse response = new TeamStatusResponse();
        response.setInTeam(inTeam);

        if (inTeam) {
            // 获取团队相关信息
            TeamMember teamMember = authService.getTeamMemberInfo(currentUserId);
            response.setTeamMember(teamMember);
        }

        return Result.ok(response);
    }

    /**
     * 团队状态响应
     */
    class TeamStatusResponse {
        private boolean inTeam;
        private TeamMember teamMember;

        // getter and setter
        public boolean isInTeam() { return inTeam; }
        public void setInTeam(boolean inTeam) { this.inTeam = inTeam; }
        public TeamMember getTeamMember() { return teamMember; }
        public void setTeamMember(TeamMember teamMember) { this.teamMember = teamMember; }
    }
}